import React, { useEffect, useState } from 'react';
import { Card, Table, Button, Space, Input, Select, Tag, Popconfirm, message, Modal } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, EyeOutlined, PlayCircleOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from '../../store';
import { fetchRuleList, deleteRule, setPage, setSize } from '../../store/slices/ruleSlice';
import type { RuleBasicInfo } from '../../types/rule';

const { Search } = Input;
const { Option } = Select;

const RuleConfig: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch<AppDispatch>();
  const { ruleList, loading, total, page, size } = useSelector((state: RootState) => state.rule);
  
  const [searchParams, setSearchParams] = useState({
    name: '',
    status: '',
    creator: '',
  });

  useEffect(() => {
    dispatch(fetchRuleList({
      page,
      size,
      ...searchParams,
    }));
  }, [dispatch, page, size, searchParams]);

  const handleSearch = () => {
    dispatch(setPage(1));
    dispatch(fetchRuleList({
      page: 1,
      size,
      ...searchParams,
    }));
  };

  const handleReset = () => {
    setSearchParams({ name: '', status: '', creator: '' });
    dispatch(setPage(1));
  };

  const handleEdit = (id: string) => {
    navigate(`/rule-config/edit/${id}`);
  };

  const handleCreate = () => {
    navigate('/rule-config/edit');
  };

  const handleDelete = async (id: string) => {
    try {
      await dispatch(deleteRule(id)).unwrap();
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };



  const handlePreview = (record: RuleBasicInfo) => {
    Modal.info({
      title: '规则详情',
      width: 800,
      content: (
        <div style={{ marginTop: 16 }}>
          <p><strong>规则名称：</strong>{record.name}</p>
          <p><strong>规则描述：</strong>{record.description || '暂无描述'}</p>
          <p><strong>状态：</strong>
            <Tag color={record.status === 'active' ? 'green' : 'red'}>
              {record.status === 'active' ? '启用' : '禁用'}
            </Tag>
          </p>
          <p><strong>创建人：</strong>{record.creator}</p>
          <p><strong>创建时间：</strong>{record.createTime}</p>
          <p><strong>更新时间：</strong>{record.updateTime}</p>
        </div>
      ),
    });
  };

  const handleExecute = (_id: string) => {
    message.info('执行功能开发中...');
  };

  const columns: ColumnsType<RuleBasicInfo> = [
    {
      title: '规则名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '规则描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_: any, record: RuleBasicInfo) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handlePreview(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            size="small"
            icon={<PlayCircleOutlined />}
            onClick={() => handleExecute(record.id!)}
          >
            执行
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record.id!)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这条规则吗？"
            onConfirm={() => handleDelete(record.id!)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              size="small"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <Space direction="vertical" style={{ width: '100%' }} size="large">
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
            <Search
              placeholder="请输入规则名称"
              allowClear
              value={searchParams.name}
              onChange={(e) => setSearchParams({ ...searchParams, name: e.target.value })}
              style={{ width: 200 }}
              onSearch={handleSearch}
            />
            <Select
              placeholder="请选择状态"
              allowClear
              value={searchParams.status}
              onChange={(value) => setSearchParams({ ...searchParams, status: value })}
              style={{ width: 120 }}
            >
              <Option value="active">启用</Option>
              <Option value="disabled">禁用</Option>
            </Select>
            <Search
              placeholder="请输入创建人"
              allowClear
              value={searchParams.creator}
              onChange={(e) => setSearchParams({ ...searchParams, creator: e.target.value })}
              style={{ width: 150 }}
              onSearch={handleSearch}
            />
            <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
              搜索
            </Button>
            <Button onClick={handleReset}>重置</Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleCreate}
              style={{ marginLeft: 'auto' }}
            >
              新建规则
            </Button>
          </div>
          
          <Table
            columns={columns}
            dataSource={ruleList}
            rowKey="id"
            loading={loading}
            pagination={{
              current: page,
              pageSize: size,
              total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
              onChange: (page, pageSize) => {
                dispatch(setPage(page));
                dispatch(setSize(pageSize));
              },
            }}
            scroll={{ x: 1200 }}
          />
        </Space>
      </Card>
    </div>
  );
};

export default RuleConfig;